package com.tarena.luban.test.repository.impl;

import com.tarena.luban.test.bo.WorkerCategoryBO;
import com.tarena.luban.test.dao.WorkerCategoryDao;
import com.tarena.luban.test.repository.WorkerCategoryRepository;
import com.tarena.luban.test.repository.converter.WorkerCategoryConverter;
import com.tarena.tp.luban.worker.po.WorkerCategory;
import com.tarena.tp.luban.worker.server.dto.param.WorkerCategoryParam;
import com.tarena.tp.luban.worker.server.dto.param.WorkerCreateParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Repository
public class WorkerCategoryRepoImpl extends RedisCacheEntry<WorkerCategoryBO> implements WorkerCategoryRepository {
    @Autowired(required = false)
    private WorkerCategoryDao workerCategoryDao;
    @Override
    public void deleteCategories(Long userId) {
        workerCategoryDao.delete(userId);
        String key="luban:worker:cat:"+userId;
        delete(key);
    }
    @Autowired
    private WorkerCategoryConverter workerCategoryConverter;
    @Override
    public void saveCategories(WorkerCreateParam workerCreateParam) {
        List<WorkerCategoryParam> workerCategoryParams = workerCreateParam.getWorkerCategoryParams();
        List<WorkerCategory> categories=new ArrayList<>();
        for (WorkerCategoryParam workerCategoryParam : workerCategoryParams) {
            WorkerCategory workerCategory = workerCategoryConverter.param2po(workerCategoryParam);
            categories.add(workerCategory);
        }
        workerCategoryDao.insertCategories(categories);
    }

    @Override
    public List<WorkerCategoryBO> findCategories(Long userId) {
        String key="luban:worker:cat:"+userId;
        Boolean exists = exists(key);
        List<WorkerCategoryBO> workerCategoryBOS=null;
        if (!exists){
            //1. 查询do
            List<WorkerCategory> categories=workerCategoryDao.selectCategoriesByUserId(userId);
            workerCategoryBOS = workerCategoryConverter.poList2BoList(categories);
            saveCaches(key,workerCategoryBOS,24L, TimeUnit.HOURS);
        }else{
            workerCategoryBOS=getCaches(key);
        }
        return workerCategoryBOS;
    }
}
